import requests, json
import datetime
import time
############################## 27012587
activityId = "2406300064205813"
inviteUid = 0
name = "刘素英"  # 接龙名
Authorization = "eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjE4MzE2MjM3MCwiZXhwIjoxNzIwMzI3ODk5fQ.PdK_jW7on7GDLlycxxEYCU-mtfXjnVrIVZP1oyeqITk58pb2yr9GFyM8UW8X_7dXFcDxA-lKRpZ4BSqkwFWYxA"
itemAttrId = 46329322
yanshi = 0.75
logname = "tb_27012587_tx.log"
##############################
info_url = "https://apipro.qunjielong.com/activity-biz/activity/detail/frame/chart"
headers = {
    "Host": "apipro.qunjielong.com",
    "Connection": "keep-alive",
    "device-type": "10",
    "mini-route": "pro/pages/seq-detail/detail-form/detail-form",
    "Authorization": Authorization,
    "uid": "183162370",
    "companyId": "190",
    "feature-tag": "f0000",
    "scene-flow": "seq-detail,4bbc123383ed6ff5f201ca2efbf9648a",
    "client-version": "5.6.20",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090b11)XWEB/9185",
    "Content-Type": "application/json",
    "xweb_xhr": "1",
    "appid": "wx059cd327295ab444",
    "sceneCode": "1256",
    "version": "3.0.0",
    "Accept": "*/*",
    "Sec-Fetch-Site": "cross-site",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Dest": "empty",
    "Referer": "https://servicewechat.com/wx059cd327295ab444/1827/page-frame.html",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9"
}
data = {
	"activityId": activityId,
	"enterStatus": 1,
	"inviteUid": inviteUid
}
proxies = {"http": None, "https": None}
stime = time.time()
res = requests.post(info_url, headers=headers, data=json.dumps(data), proxies=proxies)
print("请求时间：{}s".format(time.time() - stime))
js = res.json()
stime = datetime.datetime.now()
if js.get("data") and js.get("data").get("activity") and js.get("data").get("activity").get("startTime"):
    stime = datetime.datetime.fromtimestamp(js.get("data").get("activity").get("startTime") / 1000)
    stime -= datetime.timedelta(seconds=1)

print(stime.strftime("%Y-%m-%d %H:%M:%S"))
print("延时：" + str(yanshi))

while datetime.datetime.now() < stime:
    pass

time.sleep(yanshi)


def run(f_w):
    try:
        t1 = time.time()
        # 表格
        goodsUrl = "https://apipro.qunjielong.com/activity-biz/activity/detail/frame/chart"
        data = {
            "activityId": activityId,
            "enterStatus": 1,
            "inviteUid": inviteUid  # 139601259 霍医生
        }

        # res = requests.post(goodsUrl, headers=headers, data=json.dumps(data))
        # print(res.text)
        # js = res.json()
        # actGoodsId = js.get("data").get("activityItemAttr").get("attrItemList")[0].get("actGoodsId")
        # activityItemAttr

        # participator_fill_content = "https://apipro.qunjielong.com/activity-accessory/activity_input/participator_fill_content?actId={}".format(
        #     activityId)
        # res = requests.get(participator_fill_content, headers=headers)
        # print(res.text)
        # js = res.json()
        # return

        data = {
            "chartOrderDTO": {
                "orderDefItemList": [{
                    # "itemAttrId": js.get("data").get("chartActParticipatorFillContentDTO").get("actItemAttrs")[0].get(
                    #     "itemAttrId"),
                    "itemAttrId": itemAttrId,
                    "extensionType": 0,
                    "attrInputDTO": {
                        "type": 10,
                        "textInputDTO": {
                            "text": name
                        }
                    }
                }],
                "markInfoJson": {}
            },
            "actId": activityId
        }
        print(data)
        f_w.write(json.dumps(data) + "\n")
        place_all = "https://apipro.qunjielong.com/order-place/api/mina/order_place/place-all"
        res = requests.post(place_all, headers=headers, data=json.dumps(data), proxies=proxies)
        print(res.text)
        f_w.write(res.text + "\n")
        js = res.json()
        if js.get("data").get("success"):
            # orderNo = js.get("data").get("orderNo")
            # # 4. 获取结果 https://apipro.qunjielong.com/order-place/api/mina/order_place/query_order_pay_success_toast_list?actId=2404230269127881&orderNo=240423171385599723874877228
            # query_order_pay_success_toast_list = "https://apipro.qunjielong.com/order-place/api/mina/order_place/query_order_pay_success_toast_list?actId={}&orderNo={}".format(
            #     activityId, orderNo)
            # res = requests.get(query_order_pay_success_toast_list, headers=headers)
            # return True
            query_order_personal_home_page = "https://apipro.qunjielong.com/order-cert/api/mina/user-order/query_order_personal_home_page?page=1&pageSize=1"
            res = requests.post(query_order_personal_home_page, data=json.dumps({}), headers=headers, proxies=proxies)
            f_w.write(json.dumps(res.json(), indent=4, ensure_ascii=False, sort_keys=True))
            f_w.write("\n")
            return True
        return False

    except Exception as e:
        print(e)
        return False


def sendMsg(msg):
    baseurl = "http://101.43.46.189:5001/receiveMsg"
    data = {
        "msg": msg,
        "agentid": 1000006
    }
    headers = {
        "Content-type": "application/json"
    }
    print(msg)
    r = requests.post(baseurl, data=json.dumps(data), headers=headers)
    print(r.text)


with open(logname, "w") as f_w:
    for i in range(5):
        f_w.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") + "\n")
        if run(f_w):
            sendMsg("{}抢单成功".format(name))
            break
        time.sleep(0.2)

